package com.karrysong.blog_springboot.handle;

import com.karrysong.blog_springboot.entity.RequestRecord;
import com.karrysong.blog_springboot.enums.ErrorCode;
import com.karrysong.blog_springboot.service.RecordService;
import com.karrysong.blog_springboot.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: AllExceptionHandler
 * @Author: KarrySong
 * @Date: 2022/8/4 10:10
 * @Description:
 */
@ControllerAdvice
@Slf4j
public class AllExceptionHandler {

    @Autowired
    private RecordService recordService;

    //进行异常处理，处理Exception.class的异常
    @ExceptionHandler(Exception.class)
    @ResponseBody //返回json数据
    public Result doException(Exception ex){
        ex.printStackTrace();
        log.info(ex.getMessage());

        RequestRecord requestRecord = new RequestRecord();
        requestRecord.setRequestMethod("exception");
        requestRecord.setParams(ex.getMessage());
        requestRecord.setRequestTime(System.currentTimeMillis());
        requestRecord.setExecuteTime(-1L);
        requestRecord.setRequestIp("exception");
        requestRecord.setBrowserInfo("exception");
        requestRecord.setOsInfo("exception");
        recordService.insertRecord(requestRecord);

        return Result.fail(ErrorCode.SYSTEM_EXCEPTION,"系统异常:" + ex.getMessage());
    }
}
